package com.iweb.goods.servlet;

import com.alibaba.fastjson.JSONObject;
import com.iweb.goods.model.Goods;
import com.iweb.goods.service.GoodsService;
import com.iweb.goods.service.GoodsServiceImpl;
import com.iweb.user.model.User;
import com.iweb.util.PageModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(value = "*.goods")
public class GoodsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        switch (path){
            case"/toList.goods":
                toList(req,resp);
                break;
            case "/toMyList.goods":
                toMyList(req,resp);
                break;
            case"/selectByMyPage.goods":
                selectByMyPage(req,resp);
                break;
            case"/selectByPage.goods":
                selectByPage(req,resp);
                break;
            case "/toEdit.goods":
                toEdit(req,resp);
                break;
            case "/saveOne.goods":
                saveOne(req,resp);
                break;
            case "/queryByGoodsId.goods":
                queryByGoodsId(req,resp);
                break;
            case "/checkedGoodsName.goods":
                checkedGoodsName(req,resp);
                break;
            case "/deleteById.goods":
                deleteById(req,resp);
                break;
            case "/getCurrentUserInfo.goods":
                getCurrentUserInfo(req,resp);
                break;
            default:
                break;
        }
    }
    GoodsService goodsService=new GoodsServiceImpl();
    public void getCurrentUserInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        HttpSession session=req.getSession();
        User currentUser = (User) session.getAttribute("user");
        if (currentUser!=null){
            // 只返回需要的用户信息
            JSONObject userInfo = new JSONObject();
            userInfo.put("userid", currentUser.getUserid());
            resp.getWriter().print(userInfo.toJSONString());
        }else {
            resp.getWriter().print("");
        }
    }
    public void toList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.getRequestDispatcher("/goods/goods_selectByPage.html").forward(req,resp);
    }
    public void toMyList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.getRequestDispatcher("/goods/goods_selectByMyPage.html").forward(req,resp);
    }
    public void selectByMyPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        HttpSession session=req.getSession();
        if(session.getAttribute("user")==null){
            resp.getWriter().print("");
            return;
        }
        // 获取当前登录用户的ID
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUserid();
        String pageNo = req.getParameter("pageNo") == null?"1":req.getParameter("pageNo");
        String likeValue = req.getParameter("likeValue") == null?"":req.getParameter("likeValue");
        PageModel pageModel = new PageModel();
        pageModel.setPageNo(Integer.valueOf(pageNo));
        pageModel.setLikeValue(likeValue);

        // 调用新的服务方法，传入用户ID
        List<Goods> goodses = goodsService.selectByMyPage(pageModel, userId);
        pageModel.setRecordList(goodses);
        String jsonStr = JSONObject.toJSONString(pageModel);
        resp.getWriter().print(jsonStr);
    }

    public void selectByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        HttpSession session=req.getSession();
        if(session.getAttribute("user")==null){
            resp.getWriter().print("");
            return;
        }
        String pageNo = req.getParameter("pageNo") == null?"1":req.getParameter("pageNo");
        String likeValue = req.getParameter("likeValue") == null?"1":req.getParameter("likeValue");
        PageModel pageModel = new PageModel();
        pageModel.setPageNo(Integer.valueOf(pageNo));
        pageModel.setLikeValue(likeValue);
        List<Goods> goodses = goodsService.selectByPage(pageModel);
        pageModel.setRecordList(goodses);
        String jsonStr = JSONObject.toJSONString(pageModel);
        resp.getWriter().print(jsonStr);
    }
    public void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.getSession().setAttribute("goodsToken","goodsTokenValue");
        String goodsid=req.getParameter("goodsid");
        resp.sendRedirect(req.getContextPath()+"/goods/goods_toAdd.html?goodsid="+ goodsid);
    }
    public void saveOne(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        Object o=req.getSession().getAttribute("goodsToken");
        if(o!=null){
            req.getSession().removeAttribute("goodsToken");
            // 从session中获取当前登录用户
            User currentUser = (User) req.getSession().getAttribute("user");
            if (currentUser == null) {
                resp.sendRedirect(req.getContextPath() + "/login.html");
                return;
            }
            String goodsid=req.getParameter("goodsid");
            if(goodsid!=null && !"".equals(goodsid)){
                //修改
                String goodsname=req.getParameter("goodsname");
                String goodsprice=req.getParameter("goodsprice");
                String description =req.getParameter("description");
                Goods goods=new Goods(Integer.valueOf(goodsid),currentUser.getUserid(),goodsname,goodsprice,null,description);
                goodsService.updateOne(goods);
            }else{
                //新增
                String goodsname=req.getParameter("goodsname");
                String goodsprice=req.getParameter("goodsprice");
                String description =req.getParameter("description");
                Goods goods=new Goods(null,currentUser.getUserid(),goodsname,goodsprice, null, description);
                goodsService.saveOne(goods);
            }
            resp.sendRedirect(req.getContextPath()+"/toList.goods?pageNo=1&likeValue=");
        }else {
            resp.sendRedirect(req.getContextPath() + "/token.html");
        }
    }
    public void queryByGoodsId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String goodsid=req.getParameter("goodsid");
        Goods goods= goodsService.selectById(Integer.valueOf(goodsid));
        String jsonStr=JSONObject.toJSONString(goods);
        resp.getWriter().print(jsonStr);
    }
    public void checkedGoodsName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String goodsName=req.getParameter("goodsName");
        boolean flag=goodsService.isContainGoodsName(goodsName);
        String res="";
        if(flag)
            res="{\"flag\":1}";
        else
            res="{\"flag\":0}";
        resp.getWriter().print(res);

    }
    public void deleteById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String goodsid=req.getParameter("goodsid");
        //删除
        goodsService.deleteOne(Integer.valueOf(goodsid));
        resp.sendRedirect(req.getContextPath()+"/toList.goods?pageNo=1&likeValue=");
    }
}
